package com.liuqi.jobtask;

import cn.hutool.core.date.DateUtil;
import com.liuqi.business.model.MiningBonusPoolConfigModel;
import com.liuqi.business.model.MiningBonusPoolConfigModelDto;
import com.liuqi.business.model.MiningCensusModel;
import com.liuqi.business.service.MiningBonusPoolConfigService;
import com.liuqi.business.service.MiningCensusService;
import com.liuqi.redis.RedisRepository;
import com.liuqi.utils.DateTimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author: Mr.Liu
 * @date: 2021/3/18 9:35
 * @version: 1.0
 * @class: ContractJob
 * @desc: 合约理财统计定时任务
 */
@Slf4j
public class ContractJob implements Job {

    @Autowired
    private RedisRepository redisRepository;

    @Autowired
    private MiningBonusPoolConfigService miningBonusPoolConfigService;

    @Autowired
    private MiningCensusService miningCensusService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
        log.info("ContractJob定时任务开始执行");
        String key = "contract:" + DateTimeUtils.currentDate("yyyy-MM-dd");
        if (!redisRepository.hasKey(key)) {
            log.info("ContractJob定时任务执行");
            executeContractJob();
            redisRepository.set(key, "contract", 1, TimeUnit.DAYS);
        } else {
            log.info("ContractJob定时任务已经执行过，不在执行");
        }
        log.info("ContractJob定时任务执行结束");
    }

    /**
     * 执行合约具体业务逻辑
     */
    private void executeContractJob() {
        List<MiningBonusPoolConfigModelDto> data = miningBonusPoolConfigService.queryListByDto(null, true);
        if (CollectionUtils.isNotEmpty(data)) {
            data.forEach(param -> {
                Integer isOut = param.getIsOut();
                //出局（0 未出局，1 出局）逻辑,计算收益
                if (isOut == 1) {
                    handIsOut(param);
                }
            });
        }
    }

    /**
     * 处理正常出局逻辑，满周期加收益
     * @param param
     */
    @Transactional(rollbackFor =Exception.class)
    public void handIsOut(MiningBonusPoolConfigModelDto param) {
        MiningBonusPoolConfigModelDto byId = miningBonusPoolConfigService.getById(param.getId());
        //判断周期
        if(byId.getCycle().equals(1)){
            //计算当前周期
            String dayStr = null;
            try {
                 dayStr = TimeDiff(DateUtil.format(byId.getCreateTime(), "yyyy-MM-dd HH:mm"),DateUtil.format(new Date(), "yyyy-MM-dd HH:mm"));
            } catch (Exception e) {
               log.info("日期解析异常");
            }
            if (dayStr.equals("1")) {
                //增加0.01收益
                BigDecimal interest = byId.getPrincipal().multiply(new BigDecimal(0.01)).setScale(3, BigDecimal.ROUND_HALF_UP);
                MiningBonusPoolConfigModel changeModel = new MiningBonusPoolConfigModel();
                changeModel.setId(byId.getId());
                changeModel.setInterest(interest);
                changeModel.setTotalGold(byId.getPrincipal().add(interest));
                miningBonusPoolConfigService.update(changeModel);

                //插入理财统计表
                MiningCensusModel censusModel = new MiningCensusModel();
                censusModel.setUserId(byId.getUserId());
                censusModel.setCensusTime(new Date());
                censusModel.setCurrencyId(Integer.valueOf(byId.getCurrencyId().toString()));
                censusModel.setPrincipal(byId.getPrincipal());
                censusModel.setCycle(1);
                censusModel.setRate(new BigDecimal(0.01));
                censusModel.setInterest(changeModel.getInterest());
                censusModel.setTotalGold(changeModel.getTotalGold());
                miningCensusService.insert(censusModel);
            }
        }else {
            //计算当前周期
            String dayStr = null;
            try {
                dayStr = TimeDiff(DateUtil.format(byId.getCreateTime(), "yyyy-MM-dd HH:mm"),DateUtil.format(new Date(), "yyyy-MM-dd HH:mm"));
            } catch (Exception e) {
                log.info("日期解析异常");
            }
            if (dayStr.equals("7")) {
                //增加0.1收益
                BigDecimal interest = byId.getPrincipal().multiply(new BigDecimal(0.1)).setScale(3, BigDecimal.ROUND_HALF_UP);
                MiningBonusPoolConfigModel changeModel = new MiningBonusPoolConfigModel();
                changeModel.setId(byId.getId());
                changeModel.setInterest(interest);
                changeModel.setTotalGold(byId.getPrincipal().add(interest));
                miningBonusPoolConfigService.update(changeModel);

                //插入理财统计表
                MiningCensusModel censusModel = new MiningCensusModel();
                censusModel.setUserId(byId.getUserId());
                censusModel.setCensusTime(new Date());
                censusModel.setCurrencyId(Integer.valueOf(byId.getCurrencyId().toString()));
                censusModel.setPrincipal(byId.getPrincipal());
                censusModel.setCycle(7);
                censusModel.setRate(new BigDecimal(0.1));
                censusModel.setInterest(changeModel.getInterest());
                censusModel.setTotalGold(changeModel.getTotalGold());
                miningCensusService.insert(censusModel);
            }
        }
    }

    /**
     * 计算时间段天数
     * @param pBeginTime 开始时间
     * @param pEndTime 结束时间
     * @return
     * @throws Exception
     */
    public static String TimeDiff(String pBeginTime, String pEndTime) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Long beginL = format.parse(pBeginTime).getTime();
        Long endL = format.parse(pEndTime).getTime();
        Long day = (endL - beginL)/86400000;
        Long hour = ((endL - beginL)%86400000)/3600000;
        Long min = ((endL - beginL)%86400000%3600000)/60000;
        return String.valueOf(day);
    }
}
